package com.vista.beans.documento;

import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Order;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.comun.filtro.FiltroLista;
import com.facade.documento.IGestionDocumento;
import com.facade.utils.UtilsFacade;
import com.modelo.entity.Documento;

@Component("LazyDocumentoDataModel")
@Scope("session") //tiene que ser session para que guarde los datos en la sesion, puesto que son necesarios.
public class LazyDocumentoDataModel extends LazyDataModel<Documento> {

	private static final long serialVersionUID = 1L;
	private List<Documento> datasource;

	@Autowired
	private IGestionDocumento iGestionDocumento;
	
	public LazyDocumentoDataModel( ) {
		//this.datasource = datasource;
	}

	@Override
	public Documento getRowData(String rowKey) {
		for (Documento doc : datasource) {
			if (doc.getId().equals(Integer.valueOf(rowKey)))
				return doc;
		}

		return null;
	}

	@Override
	public Integer getRowKey(Documento doc) {
		return doc.getId();
	}

	@Override
	public List<Documento> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {
		
		Order order = UtilsFacade.convertSortOrderToOrder(sortOrder, sortField); 
		
		FiltroLista filtro = new FiltroLista(first, pageSize, order, filters);
				
		filtro.setObtenerTotal(true);			
		datasource = iGestionDocumento.getDocumentosActivos(filtro);
		
		this.setRowCount(iGestionDocumento.getTotal()); 
		
		return datasource; 
	}
	
/*	@PostConstruct
	public void init(){
		load(0,10,null,null,null);
	}
*/
	public IGestionDocumento getiGestionDocumento() {
		return iGestionDocumento;
	}

	public void setiGestionDocumento(IGestionDocumento iGestionDocumento) {
		this.iGestionDocumento = iGestionDocumento;
	}

	public void setDatasource(List<Documento> datasource) {
		this.datasource = datasource;
	}

	public List<Documento> getDatasource() {
		return datasource;
	}

}
